package com.dq.utils.gsonutils;

import com.alibaba.fastjson.JSONObject;
import com.dq.utils.gsonutils.adapter.DateNullAdapterFactory;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 *
 * 实体 - json 转换工具类
 *
 *  ###### 解决了 转换时 date类型 数据为 "" 问题 ######
 *
 * @author cf
 */
public class GsonUtils {

    /**
     * 解决了 转换时 date类型 数据为null 问题
     *
     * ignoreDateGson.fromJson(orderInfo.toString(), SyspraiseOrderInfo.class);
     */
    private final static Gson ignoreDateGson = new GsonBuilder()
            .registerTypeAdapterFactory(new DateNullAdapterFactory<>()).create();

    public static Gson getDateGson() {

        return ignoreDateGson;
    }

    /**
     * 驼峰转换
     */
    private final static Gson ignoreDateGsonHump = new GsonBuilder()
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .registerTypeAdapterFactory(new DateNullAdapterFactory<>()).create();

    public static Gson getDateGsonHump() {

        return ignoreDateGsonHump;
    }

    public static void main(String[] args) {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "名称");
        jsonObject.put("age", 18);
        jsonObject.put("time", "");
        jsonObject.put("goods_no", "123");
        jsonObject.put("goods_status", "1");

        // 解决异常
        EntityExamples entityExamples = getDateGsonHump().fromJson(jsonObject.toString(), EntityExamples.class);

        /// new Gson(): 当  jsonObject.put("time", "");时 异常
        Gson gson = new Gson();
//        User user1 = gson.fromJson(jsonObject.toString(), User.class);
        System.out.println(entityExamples.getGoodsStatus());
    }

}
